$(function() {
    $.initPage(adminUserList.load.start);
});

var adminUserList = new BaseFrame();

adminUserList.addBlock('search', 'list', 'pagination', 'detail');

//load module
adminUserList.load.addStart(function() {
    var params = adminUserList.data.search.params;
    params.isSuperUser = false;
    _user.isSuperUser = false;
    params.userFormIds = !$.isEmpty(_user.others) && !$.isEmpty(_user.others.formIds) ? _user.others.formIds : null;
    $.get(_apiPath + '/Apps/formList', params)
    .then(function(result){
        //verify if this account is superuser? it is super user when has all form privileges
        if (!$.isEmpty(result)){
            var formIds = [];
            result.forEach(function(item){
            formIds.push(item.id.toString());
            });
            var diffArray = _.difference(formIds, params.userFormIds);
            if (diffArray.length == 0){ // is super user
            params.isSuperUser = true;
            _user.isSuperUser = true;
            }
        }
        return $.get(_apiPath + '/Admins/Users/Page', params);
    })
    .then(function(data) {
         _data = $.extend({}, data);
        return $.pageStart(_adminSettings);
    })
    .then(function() {
        adminUserList.load.runTask();
        adminUserList.event.runTask();
        adminUserList.load.list.create(_data.userList);
    });
});

adminUserList.load.addBind('createTitle', function() {
    var currentPage = $.getCurrentPage(_adminSettings.pageList);
    $('title').text(currentPage.title);
});

adminUserList.load.addBind('createNav', function() {
    $('#logout').on('click', $.logoff);
    var navList = $.getUserAuthorityList(_user.roleList, _adminSettings.authorityList, _adminSettings.pageList);
    $('#block-nav').createNavList(navList).removeClass('dn');
});

adminUserList.load.list.addBind('createListTitle', function() {
    var currentPage = $.getCurrentPage(_adminSettings.pageList);
    $('#block-list .panel-title').text($.toString(currentPage.title));
});

adminUserList.load.list.addEvent('create', function(dataList) {
    if (dataList.length == 0) {
        $('#block-alert').text(_enumMessage.noSearchResult);
        $('#list-list tbody').addClass('dn');
        $('#block-alert').removeClass('dn');
        $('#block-pagination').addClass('dn');
    } else {
        var template = $('#template-list-detail').html();
        $('#list-list tbody').empty().createListTemplate(template, dataList);
        adminUserList.load.pagination.create(_data.pageTotal);
        $('#list-list tbody').removeClass('dn');
        $('#block-alert').addClass('dn');
    }
    $('#block-list').removeClass('dn');
    var params = adminUserList.data.search.params;
    if ($.isEmpty(params.userFormIds)) $('.btn[create]').addClass('dn');
});

adminUserList.load.list.addEvent('update', function(pageNumber) {
    var params = adminUserList.save.search.params();
    params.pageNumber = pageNumber || params.pageNumber;
    $.get(_apiPath + '/Admins/Users', params)
        .then(function(data) {
            if (data.pageId != adminUserList.data.search.params.pageId) return false;
            _data.userList = data.userList;
            _data.pageTotal = data.pageTotal;
            adminUserList.load.list.create(_data.userList);
        });
});

adminUserList.load.pagination.addEvent('create', function(pageTotal, pageNumber, pageSize) {
    if ($.isEmpty(pageTotal) || pageTotal < 1) return;
    pageNumber = pageNumber || adminUserList.data.search.params.pageNumber;
    pageSize = pageSize || adminUserList.data.search.params.pageSize;
    $('#block-pagination').empty().createPagination({
        pageNumber: pageNumber,
        pageTotal: pageTotal,
    }).removeClass('dn');
});

adminUserList.load.detail.addEvent('create', function(detailData) {
    var domStorage = $('#form-detail');
    domStorage.data('detail', $.extend({}, detailData));
    $('#field-detail-employeeId').empty().createString(domStorage, 'detail.employeeId', {
        required: true,
        disabled: $.isZero(detailData.id) ? false : true,
    });
    $('#field-detail-englishName').empty().createString(domStorage, 'detail.englishName', {
        required: true,
    });
    $('#field-detail-chineseName').empty().createString(domStorage, 'detail.chineseName', {
        required: true,
    });
    $('#field-detail-department').empty().createSelect(domStorage, 'detail.departmentId', $.getKeyValueListByIdName(_data.departmentList), {
        required: true,
    });
    $('#field-detail-lineManager').empty().createString(domStorage, 'detail.lineManagerId', {
        required: true,
    });
    $('#field-detail-email').empty().createEmail(domStorage, 'detail.email', {
        required: true,
    });
    $('#field-detail-mobile').empty().createMobile(domStorage, 'detail.mobile', {
        required: true,
    });
    $('#field-detail-telephone').empty().createTelephone(domStorage, 'detail.telephone', {
        required: true,
    });
    // ['admin','approver','requester']
    domStorage.data('detail').roleList = [];
    for (var i = 0; i < detailData.roleList.length; i++)
        domStorage.data('detail').roleList.push(detailData.roleList[i].id);
    var disabled = [];
    for (var i = 0; i < _data.roleList.length; i++) {
        if (_data.roleList[i].isDefault) disabled.push(_data.roleList[i].id);
        if ($.isEmpty(domStorage.data('detail').roleList)) domStorage.data('detail').roleList.push(_data.roleList[i].id);
    }
    $('#field-detail-role').empty().createCheckbox(domStorage, 'detail.roleList', $.getKeyValueListByIdName(_.take(_data.roleList, 3)), {
        required: true,
        disabled: [1, 2],
    });
    // group role list
    if (!$.isEmpty(_data.formList) && !$.isEmpty(_data.formList)){        
        _data.formList.forEach(function(item){         
          var groupTempate = '<tr class="dn" id="role-group-' + item.id  + '"><td class="pt5 pr5">' + item.formChineseName + ':</td><td class="pt5 pr5 pl5" id="role-list"></td></tr>';
          var roleList = [];
          _.forEach(_data.roleList, function(role){
              if (!_.isEmpty(role.others) && !_.isEmpty(role.others.formIds)){
                var formIds = [];
                _.forEach(role.others.formIds,function(id){
                    formIds.push(parseInt(id));
                });
                if (_.includes(formIds, item.id))
                roleList.push(role);
              }                
          });
          $('#field-detail-role').append(groupTempate);
          if (!$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds)){
            var hasForm = false;
            _.forEach(detailData.others.formIds, function(fid){
                if (parseInt(fid) == item.id){
                    if (!_.isEmpty(_user.others) && !_.isEmpty(_user.others.formIds)){
                        _.forEach(_user.others.formIds, function(ufid){
                            if (parseInt(ufid) == item.id){
                                hasForm = true;
                                return;
                            }
                        });
                    }
                    if (hasForm) return;
                }
            });
            if (hasForm){
                $('#role-group-' + item.id).removeClass('dn');
            }
          }
          domStorage.data('detail')['groupRoleList_' + item.id] = [];
          var userRoleMapList = domStorage.data('detail').roleMapList;
          _.forEach(userRoleMapList, function(map){
            if (!_.isEmpty(map.others) && !_.isEmpty(map.others.formIds)){
                _.forEach(map.others.formIds, function(fid){
                    if (parseInt(fid) == parseInt(item.id)){
                        domStorage.data('detail')['groupRoleList_' + item.id].push(parseInt(map.roleId));
                    }
                });
            } else {
                domStorage.data('detail')['groupRoleList_' + item.id].push(parseInt(map.roleId));
            }
          });
          $('#role-group-' + item.id + ' #role-list').empty().createCheckbox(domStorage, 'detail.groupRoleList_' + item.id, $.getKeyValueListByIdName(roleList));
        });
      }
    domStorage.data('detail').formIdList = [];
    var userFormList = !$.isEmpty(_user.others) && !$.isEmpty(_user.others.formIds) ? _user.others.formIds : null;
    if (!$.isEmpty(userFormList)){
      var formList = [];
    //   userFormList.forEach(function(item){
    //     formList.push({
    //       id: item,
    //       name:_.find(_data.formList, {'id': parseInt(item)}).formChineseName
    //     });
    //   });
    if (_user.isSuperUser){
        userFormList.forEach(function(item){
                formList.push({
                id: item,
                name:_.find(_data.formList, {'id': parseInt(item)}).formChineseName
                });
            });
            if (!$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds)){
            detailData.others.formIds.forEach(function(item){
                domStorage.data('detail').formIdList.push(item);
              });
            }
      } else {
        if (!$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds)){
            detailData.others.formIds.forEach(function(item){
                domStorage.data('detail').formIdList.push(item);
                formList.push({
                  id: item,
                  name:_.find(_data.formList, {'id': parseInt(item)}).formChineseName
                });
              });       
        }        
      }      
      var options = {required: true};
      if (_user.isSuperUser) options = {required: true, allSelected:true}
      $('#field-detail-form').empty().createCheckbox(domStorage, 'detail.formIdList', $.getKeyValueListByIdName(formList), options);
      if(!_user.isSuperUser){
        formList.forEach(function(item){
            var hasForm = false;
            userFormList.forEach(function(ufid){
                if (ufid == item.id){
                    hasForm = true;
                    return;
                }
            });
            if (!hasForm)
                $('#field-detail-form input:checkbox[value=' + item.id + ']').parent().addClass('dn');
          });
      }
      $('#field-detail-form').on('changeCallback', function(){
        var checkboxList = $('#field-detail-form input:checkbox[value!=""]');
        for (var i = 0; i < checkboxList.length; i++){
            if (checkboxList.eq(i).is(':checked')){
                $('#role-group-' + checkboxList.eq(i).val()).removeClass('dn');
            } else {
                $('#role-group-' + checkboxList.eq(i).val() + ' input:checkbox').prop('checked', false);
                $('#role-group-' + checkboxList.eq(i).val()).addClass('dn');
                domStorage.data('detail')['groupRoleList_' + checkboxList.eq(i).val()] = [];
            }
        }
      });
    }
    $('#field-detail-status').empty().createSingleCheckbox(domStorage, 'detail.status', {
        reverse: true,
        isNumber: true,
    });
});

adminUserList.load.addEvent('roleList', function(roleList) {
    _.uniq(roleList, 'name');
    var roleNameList = '';
    for (var i = 0; i < roleList.length; i++) {
        roleNameList += ',' + roleList[i].name;
    }
    return roleNameList.replace(',', '');
});

adminUserList.load.addEvent('status', function(status) {
    if ($.isZero(status)) return '激活';
    return '未激活';
});

adminUserList.load.addEvent('formList', function(others) {
    var formNameList = '';
    if (!$.isEmpty(others) && !$.isEmpty(others.formIds)){
      for (var i = 0; i < others.formIds.length; i++) {
        _data.formList.forEach(function(item){
          if (others.formIds[i] == item.id){
            if (!formNameList.includes(item.formChineseName)) {
              formNameList += ',' + item.formChineseName;
            }
          }
        });
      }
    } 
    return formNameList.replace(',', ' ');
  });

//event module
adminUserList.event.list.addBind('operation', function() {
    $('#list-list').on('click', '.btn[create]', function() {
        var detailData = $.extend({}, adminUserList.data.detail.params);
        adminUserList.load.detail.create(detailData);
        $('#modal-detail').modal('show');
    });

    $('#list-list').on('click', '.btn[update]', function() {
        var detailData = $.extend({}, adminUserList.data.detail.params, $(this).parents('tr[data]').data('data'));
        adminUserList.load.detail.create(detailData);
        //var userFormIds = !$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds) ? detailData.others.formIds : null;
        //verify if this account is superuser? disable all role/form checkbox list when it is super user
        // if (!$.isEmpty(_data.formList)){
        //     var formIds = [];
        //     _data.formList.forEach(function(item){
        //         formIds.push(item.id.toString());
        //     });
        //     var diffArray = _.difference(formIds, userFormIds);
        //     if (diffArray.length == 0){ // is super user
        //         $('#field-detail-form input:checkbox, #field-detail-role input:checkbox').attr("disabled","disabled");
        //     }
        // }
        $('#modal-detail').modal('show');
    });

    $('#list-list').on('click', '.btn[delete]', function() {
        var detailData = $.extend({}, $(this).parents('tr[data]').data('data'));
        $.confirm(adminUserList.message.list.deleteDetail, function() {
            adminUserList.form.deleteDetail(detailData);
        });
    });
});

adminUserList.event.pagination.addBind('operation', function() {
    $('#block-pagination').on('changeCallback', function(event, currentPage, targetPage) {
        adminUserList.load.list.update(targetPage)
    });
});

adminUserList.event.detail.addBind('operation', function() {
    $('#modal-detail').on('submit', '#form-detail', function(event) {
        var thisDom = $(this);
        var params = thisDom.data('detail');
        var others = _.isEmpty(params.others) ? {} : params.others;
        _.assign(others, {'formIds': params.formIdList});
        params.others = others;
        thisDom.find('[form]').findFormUnit().verifyClean();
        if (!adminUserList.verify.detail.params(params)) return false;
        adminUserList.form.saveDetail(params);
        return false;
    });
});

//form module
adminUserList.form.addEvent('saveDetail', function(params) {
    var finalRoleList = []; 
    console.log(params);
    if (!_.isEmpty(params.roleList)){
        _.forEach(params.roleList,function(rid){
            finalRoleList.push({
                'id': parseInt(rid),
                'others': null
            });
        })
    }
    if (!_.isEmpty(params.others)&&!_.isEmpty(params.others.formIds)){            
        _.forEach(params.others.formIds, function(id){
            var groupRoleList = params['groupRoleList_' + id];
            if (!_.isEmpty(groupRoleList)){
                _.forEach(groupRoleList, function(rid){
                    var role = _.find(finalRoleList, {'id': parseInt(rid)});
                    if (!_.isEmpty(role)){
                        if (!_.isEmpty(role.others) && !_.isEmpty(role.others.formIds)){
                            role.others.formIds.push(parseInt(id))
                            _.uniq(role.others.formIds);
                        } else {
                            _.assign(role.others, {'formIds': [parseInt(id)]});
                        }
                    } else {
                        finalRoleList.push({
                            'id': parseInt(rid),
                            'others': {'formIds': [parseInt(id)]}
                        });
                    }
                });
            }
        });
    }
    params.finalRoleList = finalRoleList;
    $.post(_apiPath + '/Admins/Users/' + params.id + '/Save', params)
        .done(function(result) {
            if (_user.id === params.id) { 
                var others = _.isEmpty(_user.others) ? {} : _user.others;
                _user.others = { formIds: params.formIdList }; 
                window.sessionStorage.setItem('user', JSON.stringify(_user)); 
            }
            $('#modal-detail').modal('hide');
            $.alert(_enumMessage.saveSuccess, adminUserList.load.list.update);
        });
});

adminUserList.form.addEvent('deleteDetail', function(params) {
    $.delete(_apiPath + '/Admins/Users/' + params.id + '/Delete', params)
        .done(function(result) {
            $.alert(_enumMessage.deleteSuccess, adminUserList.load.list.update);
        });
});

adminUserList.load.search.addBind('create', function() {
    // if (eLancoApprovalList.verify.isSubmitModel()) return;
    var domStorage = $('#form-search');
    $('#field-search-Keywords').createString(domStorage, 'search.keywords', $.getKeyValueList('id', 'formChineseName', _data.formList), {
        verify: false,
    });
  
    $('#block-search .search-item[formId]').hide();
    $('#block-search').removeClass('dn');
  });
  
  //save module
  adminUserList.save.search.addEvent('params', function(pageNumber) {
    var data = $('#form-search').data();
    pageNumber = pageNumber || adminUserList.data.search.params.pageNumber;
    adminUserList.data.search.params.pageId++;
    adminUserList.data.search.params.pageNumber = pageNumber;
    adminUserList.data.search.params.keywords = data.search.keywords;
    adminUserList.data.search.params.userFormIds = _user.others.formIds; 
    adminUserList.data.search.params.isSuperUser = data.search.keywords ? 'false' : 'true';
    return adminUserList.data.search.params;
  });
  
  adminUserList.event.search.addBind('operation', function() {
    $('#block-search').on('click', '#search-btn', function() {
        adminUserList.load.list.update(1);
        return false;
    });
  });

//verify module
adminUserList.verify.detail.addEvent('params', function(params) {
    var judge = true;
    if ($.isEmpty(params.employeeId)) {
        judge = false;
        $('#field-detail-employeeId').verifyErrorAndHelp(adminUserList.message.detail.employeeIdRequired);
    }
    if ($.isEmpty(params.englishName)) {
        judge = false;
        $('#field-detail-englishName').verifyErrorAndHelp(adminUserList.message.detail.englishNameRequired);
    }
    if ($.isEmpty(params.chineseName)) {
        judge = false;
        $('#field-detail-chineseName').verifyErrorAndHelp(adminUserList.message.detail.chineseNameRequired);
    }
    if ($.isEmpty(params.email)) {
        judge = false;
        $('#field-detail-email').verifyErrorAndHelp(adminUserList.message.detail.emailRequired);
    } else {
        if (!$.isEmail(params.email)) {
            judge = false;
            $('#field-detail-email').verifyErrorAndHelp(adminUserList.message.detail.emailInvalid);
        }
    }
    if (!$.isEmpty(params.mobile) && !$.isMobile(params.mobile)) {
        judge = false;
        $('#field-detail-mobile').verifyErrorAndHelp(adminUserList.message.detail.mobileInvalid);
    }
    if (!$.isEmpty(params.telephone) && !$.isMobile(params.telephone)) {
        judge = false;
        $('#field-detail-telephone').verifyErrorAndHelp(adminUserList.message.detail.telephoneInvalid);
    }
    if ($.isEmpty(params.formIdList)) {
        judge = false;
        $('#field-detail-form').verifyErrorAndHelp(adminUserList.message.detail.formListRequired);
      }
    return judge;
});

//message module
adminUserList.message.list.addConfig('deleteDetail', '是否删除detail');

adminUserList.message.detail.addConfig('employeeIdRequired', '员工编号必填');
adminUserList.message.detail.addConfig('englishNameRequired', '英文名称必填');
adminUserList.message.detail.addConfig('chineseNameRequired', '中文名称必填');
adminUserList.message.detail.addConfig('emailRequired', '邮箱必填');
adminUserList.message.detail.addConfig('emailInvalid', '邮箱格式不正确');
adminUserList.message.detail.addConfig('mobileInvalid', '邮箱格式不正确');
adminUserList.message.detail.addConfig('telephoneInvalid', '邮箱格式不正确');
adminUserList.message.detail.addConfig('formListRequired', '可见表单必填');

// //data module
adminUserList.data.search.addConfig('params', {
    pageId: 0,
    pageNumber: 1,
    pageSize: 8,
});

adminUserList.data.detail.addConfig('params', {
    id: 0,
    employeeId: '',
    englishName: '',
    chineseName: '',
    email: '',
    mobile: '',
    telephone: '',
    roleList: [],
    status: 0,
    formIdList: [],
});